package bma.common.langutil.jmshell.common;

import java.util.ArrayList;
import java.util.List;

import bma.common.langutil.jmshell.JMShellUtil;
import bma.common.langutil.jmshell.Session;

public class JMSPager {

	public static interface Render<TYPE> {

		public void show(Session s, TYPE obj, int pos);
	}

	protected ArrayList<Object> results;
	protected int position = -1;
	protected int size = -1;

	public int getSize() {
		return size;
	}

	public void setSize(int size) {
		this.size = size;
	}

	public List<Object> getResults() {
		return results;
	}

	public int getPosition() {
		return position;
	}

	public void setPosition(int position) {
		this.position = position;
	}

	public static JMSPager getData(Session session, String namePrev,
			boolean sure) {
		return JMShellUtil.getData(session, namePrev + "_pager",
				JMSPager.class, sure);
	}

	public void reset() {
		this.position = -1;
		if (this.results != null)
			this.results.clear();
		this.results = null;
	}

	public void init(List<?> list) {
		this.position = -1;
		this.results = new ArrayList<Object>(list);
	}

	public int total() {
		return this.results == null ? 0 : this.results.size();
	}

	public <TYPE> void show(Session s, int pos, int sz, Render<TYPE> render,
			Class<TYPE> cls) {
		ArrayList<Object> lt = results;
		if (lt == null || lt.isEmpty()) {
			s.writeln("-- no data --");
			return;
		}
		if (pos == -1) {
			pos = this.position;
		}
		if (pos == -1) {
			pos = 0;
		}
		if (sz == -1) {
			sz = this.size;
		}
		if (sz == -1) {
			sz = 10;
		}
		int end = Math.min(pos + sz, lt.size());
		int i;
		s.writeln("-- " + pos + "," + end + " --");
		for (i = pos; i < end; i++) {
			if (i < lt.size()) {
				Object o = lt.get(i);
				render.show(s, cls.cast(o), i);
			} else {
				break;
			}
		}
		if (i >= lt.size()) {
			this.position = -1;
			s.writeln("-- data end --");
		} else {
			this.position = i;
			s.writeln("-- remain " + (lt.size() - this.position) + " --");
		}
	}
}
